package com.sdruixinggroup.mondayb2b.ui.fragments;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.sdruixinggroup.mondayb2b.API.API;
import com.sdruixinggroup.mondayb2b.R;
import com.sdruixinggroup.mondayb2b.adapter.ShoppingCartAdapter;
import com.sdruixinggroup.mondayb2b.interfaces.ObjectCallBack;
import com.sdruixinggroup.mondayb2b.models.ShoppingCartBeen;
import com.sdruixinggroup.mondayb2b.models.ShoppingCartMessage;
import com.sdruixinggroup.mondayb2b.ui.Activities.EditOrderFormActivity;
import com.sdruixinggroup.mondayb2b.utils.UserInfoUtil;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.leefeng.lfrecyclerview.LFRecyclerView;
import okhttp3.Call;

import static com.sdruixinggroup.mondayb2b.utils.DisplayUtil.double2String;
import static com.sdruixinggroup.mondayb2b.utils.UserInfoUtil.TOKEN_OUT_TIME;
import static com.sdruixinggroup.mondayb2b.utils.UserInfoUtil.TOKEN_OUT_TIME_ERROR;
import static com.sdruixinggroup.mondayb2b.widget.MineGoodsView.FINISH_EDITOR;

/**
 * Created by 00029935 on 2017/11/18.
 */

public class ShoppingCartFragment extends BaseFragment {
    @BindView(R.id.ib_back)
    ImageView ibBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_right)
    TextView tvRight;
    @BindView(R.id.recyclerView)
    LFRecyclerView recyclerView;
    @BindView(R.id.loading)
    ProgressBar loading;
    @BindView(R.id.check_all)
    CheckBox checkAll;
    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_accounts)
    TextView tvAccounts;
    @BindView(R.id.rl_accounts)
    RelativeLayout rlAccounts;
    @BindView(R.id.tv_empty_view)
    TextView tvEmptyView;

    private ShoppingCartAdapter adapter;
    private List<ShoppingCartBeen.MerchantsBean> data;
    private Boolean editStatus = false;
    private double totalPrice = 0;
    private int totalCount = 0;
    public static final int REFLUSH_SELECT_COUNT = 0x10026;
    public static final int REFLUSH_COUNT = 0x10027;
    private int shopCartGoodsCount = 0;
    private int shopCartGoodsCountSelect = 0;
    private Boolean isFromGoodsMsg = false;
    private Boolean isShowBackKey = false;

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            tvMoney.setText("合计：¥ " + double2String(totalPrice));
            tvAccounts.setText("去结算(" + totalCount + ")");
            ShoppingCartMessage shoppingCartMessage = new ShoppingCartMessage();
            shoppingCartMessage.count = totalCount;
            EventBus.getDefault().post(shoppingCartMessage);
            if(shopCartGoodsCount == shopCartGoodsCountSelect){
                checkAll.setChecked(true);
            }else {
                checkAll.setChecked(false);
            }
        }
    };
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        isShowBackKey = getActivity().getIntent().getBooleanExtra("isShowBackKey",false);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Object resp) {/* Do something */

        if (resp instanceof Integer) {

            int params = (Integer) resp;
            switch (params) {
                case REFLUSH_SELECT_COUNT:
                    reflushTotalCount();
                    break;
                case REFLUSH_COUNT:
                    queryData();
                    break;
            }

        }

    }

    @Override
    protected int getInflateLayout() {
        return R.layout.shopping_cart_fragment;
    }

    @Override
    protected void setUpView(View view) {
        ibBack.setImageResource(R.mipmap.share_back);

        ibBack.setVisibility( isShowBackKey?View.VISIBLE: View.GONE);
        tvTitle.setText("购物车");
        tvRight.setText("编辑");
        tvRight.setTextColor(0xff999999);
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editStatus = !editStatus;
                if (editStatus) {
                    tvRight.setText("完成");
                    rlAccounts.setVisibility(View.GONE);
                    reflushTotalCount();
                } else {
                    tvRight.setText("编辑");
                    rlAccounts.setVisibility(View.VISIBLE);
                    EventBus.getDefault().post(FINISH_EDITOR);
                    queryData();
                }

                if (!data.isEmpty()) {
                    for (ShoppingCartBeen.MerchantsBean merchantsBean : data) {
                        merchantsBean.isEditabe = editStatus;
                        List<ShoppingCartBeen.MerchantsBean.ShoppingCartsBean> goods = merchantsBean.getShopping_carts();
                        if (null != goods && !goods.isEmpty()) {
                            for (ShoppingCartBeen.MerchantsBean.ShoppingCartsBean shoppingCartsBean : goods) {
                                shoppingCartsBean.isEditabe = editStatus;
                            }
                        }
                    }
                    adapter.reflashData(data);
                }

            }
        });


        checkAll.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
              Boolean isChecked=  checkAll.isChecked();
                if (!data.isEmpty()) {
                    for (ShoppingCartBeen.MerchantsBean merchantsBean : data) {
                        merchantsBean.isSelect = isChecked;
                        List<ShoppingCartBeen.MerchantsBean.ShoppingCartsBean> goods = merchantsBean.getShopping_carts();
                        if (null != goods && !goods.isEmpty()) {
                            for (ShoppingCartBeen.MerchantsBean.ShoppingCartsBean shoppingCartsBean : goods) {
                                shoppingCartsBean.isSelect = isChecked;
                            }
                        }
                    }
                    adapter.reflashData(data);
                }
            }
        });

        adapter = new ShoppingCartAdapter(getContext());
        data = new ArrayList<>();

        adapter.setData(data);
        adapter.setOnDeleteListener(new ShoppingCartAdapter.OnDeleteListener() {
            @Override
            public void listener(ShoppingCartBeen.MerchantsBean itemData, int position) {
                Log.e("HQQ", "  aaa  position");
                showDialog();
            }
        });

        adapter.setOnDeleteGoodListener(new ShoppingCartAdapter.OnDeleteGoodListener() {
            @Override
            public void deleteGood(ShoppingCartBeen.MerchantsBean.ShoppingCartsBean shoppingCartsBean, int position) {


            }
        });


        recyclerView.setAdapter(adapter);
        recyclerView.setLoadMore(false);
        recyclerView.setLFRecyclerViewListener(new LFRecyclerView.LFRecyclerViewListener() {
            @Override
            public void onRefresh() {
                queryData();

            }

            @Override
            public void onLoadMore() {

            }
        });

        adapter.setOnShopSelectAllorNot(new ShoppingCartAdapter.OnShopSelectAllorNot() {
            @Override
            public void listener() {
                reflushTotalCount();
            }
        });
        queryData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @OnClick(R.id.ib_back)
    public void onClick() {
        getActivity().finish();
    }

    @OnClick(R.id.tv_accounts)
    public void onClickAccounts() {
        boolean check=false;
        for (ShoppingCartBeen.MerchantsBean merchantsBean : data) {
            List<ShoppingCartBeen.MerchantsBean.ShoppingCartsBean> shoppingCartsBeans = merchantsBean.getShopping_carts();
            for (ShoppingCartBeen.MerchantsBean.ShoppingCartsBean shoppingCartsBean : shoppingCartsBeans) {
                if (shoppingCartsBean.isSelect) {
                    if(shoppingCartsBean.getBuy_limit() > shoppingCartsBean.getQuantity()){
                        showMsgToast(shoppingCartsBean.getGoods().getName() +"起购数量为: "+shoppingCartsBean.getBuy_limit());
                        return;
                    }
                }
            }
        }
        if(totalCount==0){
            showMsgToast("您还没有选择要结算的商品");
            return;
        }


        Intent intent = new Intent(getContext(), EditOrderFormActivity.class);
        intent.putExtra("goods", (Serializable) adapter.getListData());
        intent.putExtra("price", totalPrice);
        startActivity(intent);
    }

    private void queryData() {
        if(isFirstIn){
           // loading.setVisibility(View.VISIBLE);
            isFirstIn = false;
        }

        String url = API.SHOPPING_CARTS + UserInfoUtil.getInfoToken(getContext()) + "&area_id="+UserInfoUtil.AREA_CODE;
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Accept", "*/*");

        TypeToken<ShoppingCartBeen> typeToken = new TypeToken<ShoppingCartBeen>() {
        };
        OkHttpUtils.get().url(url).headers(headers).build().execute(new ObjectCallBack<ShoppingCartBeen>(typeToken) {
            @Override
            public void onError(Call call, Exception e, int id) {

                if (null != loading) {
                    loading.setVisibility(View.GONE);
                }
                if (null != recyclerView) {
                    recyclerView.stopRefresh(false);
                }
            }

            @Override
            public void onResponse(ShoppingCartBeen response, int id) {
                data.clear();
                if (null != response) {
                    if (response.getErr_code() == 0) {
                        List<ShoppingCartBeen.MerchantsBean> merchantsBeans = response.getMerchants();

                        if (null != merchantsBeans && !merchantsBeans.isEmpty()) {
                            data.addAll(merchantsBeans);
                            rlAccounts.setVisibility(View.VISIBLE);
                            tvEmptyView.setVisibility(View.GONE);
                            tvRight.setVisibility(View.VISIBLE);
                        } else {
                            rlAccounts.setVisibility(View.GONE);
                            tvEmptyView.setVisibility(View.VISIBLE);
                            tvRight.setVisibility(View.GONE);
                        }
                    }  else if(response.getErr_code() == TOKEN_OUT_TIME ||response.getErr_code() == TOKEN_OUT_TIME_ERROR){
                        UserInfoUtil.intoLogin(getActivity());
                    }

                    else {
                        showMsgToast(response.getErr_msg());
                    }
                }
                adapter.reflashData(data);
                reflushTotalCount();
                if (null != recyclerView) {
                    recyclerView.stopRefresh(true);
                }
                if (null != loading) {
                    loading.setVisibility(View.GONE);
                }
            }
        });
    }


    private void showDialog() {
        AlertDialog dialog = new AlertDialog.Builder(getContext()).setTitle("提示")
                .setMessage("您确定要删除这个商品吗？")
                .setNeutralButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                }).create();

        dialog.show();
    }


    private void reflushTotalCount() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                totalPrice = 0;
                totalCount = 0;
                shopCartGoodsCount = 0;
                shopCartGoodsCountSelect=0;
                List<ShoppingCartBeen.MerchantsBean> merchantsBeans = data;
                for (ShoppingCartBeen.MerchantsBean merchantsBean : merchantsBeans) {
                    List<ShoppingCartBeen.MerchantsBean.ShoppingCartsBean> shoppingCartsBeen = merchantsBean.getShopping_carts();
                    for (ShoppingCartBeen.MerchantsBean.ShoppingCartsBean shoppingCartsBean : shoppingCartsBeen) {
                        if (shoppingCartsBean.isSelect) {
                            int count = shoppingCartsBean.getQuantity();
                            double price = shoppingCartsBean.getGoods().getSale_price();
                            totalPrice += count * price;
                           // totalCount += count;
                            ++totalCount ;
                            ++shopCartGoodsCountSelect;
                        }
                        ++shopCartGoodsCount;
                    }
                }

                if(null!= getActivity()){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tvMoney.setText("合计：¥ " + double2String(totalPrice));
                            tvAccounts.setText("去结算(" + totalCount + ")");
                            ShoppingCartMessage shoppingCartMessage = new ShoppingCartMessage();
                            shoppingCartMessage.count = totalCount;
                            EventBus.getDefault().post(shoppingCartMessage);
                            if(shopCartGoodsCount == shopCartGoodsCountSelect){
                                checkAll.setChecked(true);
                            }else {
                                checkAll.setChecked(false);
                            }
                        }
                    });
                }else {
                    handler.sendEmptyMessage(1);
                }

            }
        }).start();
    }



}
